package mxmf.utils;

import java.io.Serializable;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;

import chances.smart.commons.exception.SmartEagleException;
import chances.smart.commons.rest.RestResponse;

/**
 * 
 * @author zhangxb
 *
 */
@Component
public class RestTemplateHelper {
    private static final Logger logger = LoggerFactory.getLogger(RestTemplateHelper.class);

    @Autowired
    private RestTemplate restTemplate;

    public <T extends RestResponse> T post(String url, Serializable s, Class<T> returnClass) {
        return exchange(url, null, s, HttpMethod.POST, returnClass);
    }

    public <T extends RestResponse> T post(String url, String userId, Serializable s,
            Class<T> returnClass) {
        return exchange(url, userId, s, HttpMethod.POST, returnClass);
    }

    public <T extends RestResponse> T get(String url, Class<T> returnClass) {
        return exchange(url, null, null, HttpMethod.GET, returnClass);
    }

    public <T extends RestResponse> T exchange(String url, String userId, Serializable s,
            HttpMethod m, Class<T> returnClass) {
        HttpHeaders requestHeaders = createHeader(userId);
        HttpEntity<Serializable> requestEntity = new HttpEntity<>(s, requestHeaders);
        try {
            ObjectMapper mapper = new ObjectMapper();
            logger.info("invoke url:{},body:{}", url, mapper.writeValueAsString(s));

            ResponseEntity<T> response = restTemplate.exchange(url, m, requestEntity, returnClass);
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody();
            } else {
                throw new SmartEagleException(SmartEagleException.SOURCE_CMS,
                        SmartEagleException.MODULE_HTTP_INVOKE, response.toString());
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            throw new SmartEagleException(SmartEagleException.SOURCE_CMS,
                    SmartEagleException.MODULE_HTTP_INVOKE, e.toString());
        }

    }

    private HttpHeaders createHeader(String userId) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("userId", StringUtils.isNotBlank(userId) ? userId : "unknow");
        requestHeaders.add("Content-Type", "application/json;charset=UTF-8");
        return requestHeaders;
    }

    public <T> T getForObject(String url, Class<T> responseType, Object... uriVariables) {
        return restTemplate.getForObject(url, responseType, uriVariables);
    }

}
